import logging
from datetime import datetime
# from utils.common_logger import logger

class AccessLoggingMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        self.logger = logging.getLogger('access_log')

    def __call__(self, request):
        response = self.get_response(request)

        # 记录访问信息
        self.log_access(request, response)

        return response

    def log_access(self, request, response):
        log_data = {
            'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'method': request.method,
            'path': request.path,
            'status_code': response.status_code,
            'ip_address': self.get_client_ip(request),
        }

        log_message = f"[{log_data['timestamp']}] {log_data['ip_address']} - {log_data['method']} {log_data['path']} - {log_data['status_code']}"
        # print(111111)
        # 写入日志文件
        self.logger.info(log_message)

    def get_client_ip(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip
